package com.xiuyi.pixsynergybackend.controller.user;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiuyi.pixsynergybackend.annotation.AuthCheck;
import com.xiuyi.pixsynergybackend.common.BaseResponse;
import com.xiuyi.pixsynergybackend.common.DeleteRequest;
import com.xiuyi.pixsynergybackend.common.ResultUtils;
import com.xiuyi.pixsynergybackend.constant.UserConstant;
import com.xiuyi.pixsynergybackend.controller.user.vo.*;
import com.xiuyi.pixsynergybackend.dal.dataobject.user.UserDO;
import com.xiuyi.pixsynergybackend.exception.BusinessException;
import com.xiuyi.pixsynergybackend.exception.ErrorCode;
import com.xiuyi.pixsynergybackend.exception.ThrowUtils;
import com.xiuyi.pixsynergybackend.service.user.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 用户注册
     *
     * @param userRegisterReqVO
     * @return
     */
    @PostMapping("/register")
    public BaseResponse<Long> registerUser(@RequestBody UserRegisterReqVO userRegisterReqVO) {
        ThrowUtils.throwIf(userRegisterReqVO == null, ErrorCode.NOT_FOUND_ERROR);
        long result = userService.userRegister(userRegisterReqVO);
        return ResultUtils.success(result);
    }

    /**
     * 用户登录
     *
     * @param userLoginReqVO
     * @param request
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<UserLoginRespVO> loginUser(@RequestBody UserLoginReqVO userLoginReqVO, HttpServletRequest request) {
        ThrowUtils.throwIf(userLoginReqVO == null, ErrorCode.NOT_FOUND_ERROR);
        UserLoginRespVO userLoginRespVO = userService.userLogin(userLoginReqVO, request);
        return ResultUtils.success(userLoginRespVO);
    }

    /**
     * 获取当前已登录的用户
     *
     * @param request
     * @return
     */
    @GetMapping("/get/login")
    public BaseResponse<UserLoginRespVO> getLoginUser(HttpServletRequest request) {
        UserDO loginUser = userService.getLoginUser(request);
        return ResultUtils.success(userService.getLoginUserVO(loginUser));
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Boolean> logout(HttpServletRequest request) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);
        boolean result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 创建用户（仅限管理员）
     *
     * @param userAddReqVO
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addUser(@RequestBody UserAddReqVO userAddReqVO) {
        ThrowUtils.throwIf(userAddReqVO == null, ErrorCode.PARAMS_ERROR);
        UserDO userDO = new UserDO();
        BeanUtils.copyProperties(userAddReqVO, userDO);
        // 默认密码
        final String DEFAULT_PASSWORD = "12345678";
        String encryptPassword = userService.getEncryptPassword(DEFAULT_PASSWORD);
        userDO.setUserPassword(encryptPassword);
        // 插入数据库
        boolean result = this.userService.save(userDO);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(userDO.getId());
    }

    /**
     * 根据用户ID 获取用户（仅限管理员）
     *
     * @param id 用户ID
     * @return
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<UserDO> getUserById(Long id) {
        ThrowUtils.throwIf(id == null, ErrorCode.PARAMS_ERROR);
        UserDO userDO = userService.getById(id);
        ThrowUtils.throwIf(userDO == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(userDO);
    }

    /**
     * 根据用户ID 获取包装类（脱敏）
     *
     * @param id 用户ID
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<UserVO> getUserVOById(Long id) {
        ThrowUtils.throwIf(id == null, ErrorCode.PARAMS_ERROR);
        UserDO userDO = userService.getById(id);
        ThrowUtils.throwIf(userDO == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(userService.getUserVO(userDO));
    }

    /**
     * 删除用户（仅限管理员）
     *
     * @param deleteRequest
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = userService.removeById(deleteRequest.getId());
        return ResultUtils.success(result);
    }

    /**
     * 更新用户（仅限管理员）
     *
     * @param userUpdateReqVO
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> addUser(@RequestBody UserUpdateReqVO userUpdateReqVO) {
        if (userUpdateReqVO == null || userUpdateReqVO.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserDO userDO = new UserDO();
        BeanUtils.copyProperties(userUpdateReqVO, userDO);
        // 更新数据库
        boolean result = this.userService.updateById(userDO);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 分页获取用户（脱敏）的列表（仅限管理员）
     *
     * @param userQueryReqVO
     * @return
     */
    @PostMapping("/list/page/vo")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<UserVO>> listUserVOByPage(@RequestBody UserQueryReqVO userQueryReqVO){
        ThrowUtils.throwIf(userQueryReqVO == null, ErrorCode.PARAMS_ERROR);
        long current = userQueryReqVO.getCurrent();
        long pageSize = userQueryReqVO.getPageSize();
        Page<UserDO> userDOPage = userService.page(new Page<>(current, pageSize), userService.getQueryWrapper(userQueryReqVO));
        Page<UserVO> userVOPage = new Page<>(current, pageSize, userDOPage.getTotal());
        List<UserVO> userVOList = userService.getUserVOList(userDOPage.getRecords());
        userVOPage.setRecords(userVOList);
        return ResultUtils.success(userVOPage);
    }

}
